package io.github.annyylxyms.gynregistry;

import io.github.annyylxyms.gynregistry.cluster.Cluster;
import io.github.annyylxyms.gynregistry.cluster.Server;
import io.github.annyylxyms.gynregistry.cluster.Snapshot;
import io.github.annyylxyms.gynregistry.model.InstanceMeta;
import io.github.annyylxyms.gynregistry.service.GynRegistryService;
import io.github.annyylxyms.gynregistry.service.RegistryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * Rest Controller for registry service
 */
@Slf4j
@RestController
public class GynRegistryController {
    @Autowired
    RegistryService registryService;

    @Autowired
    Cluster cluster;

    @RequestMapping("/reg")
    public InstanceMeta register(@RequestParam String service, @RequestBody InstanceMeta instance) {
        log.info(" ===> register {} @ {}", service, instance);
        checkLeader();
        return registryService.register(service, instance);
    }

    private void checkLeader() {
        if (!cluster.self().isLeader()) {
            throw new RuntimeException("current server is not leader, the leader is " + cluster.leader().getUrl());

        }
    }

    @RequestMapping("/unreg")
    public InstanceMeta unregister(@RequestParam String service, @RequestBody InstanceMeta instance) {
        log.info(" ===> unregister {} @ {}", service, instance);
        checkLeader();
        return registryService.unregister(service, instance);
    }

    @RequestMapping("/findAll")
    public List<InstanceMeta> findAllInstances(@RequestParam String service) {
        log.info(" ===> findAllInstances {}", service);
        return registryService.getAllInstances(service);
    }

    @RequestMapping("/renew")
    public long renew(@RequestParam String service, @RequestBody InstanceMeta instance) {
        log.info(" ===> renew {} @ {}", service, instance);
        checkLeader();
        return registryService.Renew(instance, service);
    }

    @RequestMapping("/renews")
    public long renews(@RequestParam String services, @RequestBody InstanceMeta instance) {
        log.info(" ===> renews {} @ {}", services, instance);
        checkLeader();
        return registryService.Renew(instance, services.split(","));
    }

    @RequestMapping("/version")
    public long version(@RequestParam String service) {
        log.info(" ===> version {}", service);
        return registryService.version(service);
    }

    @RequestMapping("/versions")
    public Map<String, Long> versions(@RequestParam String services) {
        log.info(" ===> versions {}", services);
        return registryService.versions(services.split(","));
    }

    /**
     * 返回当前节点的信息，用于探活和对比所有节点的版本号信息
     * @return
     */
    @RequestMapping("/info")
    public Server info() {
        log.info(" ===> info {}", cluster.self());
        return cluster.self();
    }

    /**
     * 返回集群内所有节点的信息
     * @return
     */
    @RequestMapping("/cluster")
    public List<Server> cluster() {
        log.info(" ===> info {}", cluster.getServers());
        return cluster.getServers();
    }

    /**
     * 获取当前主节点（未必准，当前正在选主就不准）
     * @return
     */
    @RequestMapping("/leader")
    public Server leader() {
        log.info(" ===> info {}", cluster.leader());
        return cluster.leader();
    }


    /**
     * 设置多个主节点用来验证问题
     * @return
     */
    @RequestMapping("/setLeader")
    public Server setLeader() {
        cluster.self().setLeader(true);
        return cluster.self();
    }

    @RequestMapping("/snapshot")
    public Snapshot snapshot() {
        return GynRegistryService.snapshot();
        /*这是一个快照例子{
            "TIMESTAMPS": {
            "io.github.annyylxyms.gynrpc.UserService": 9
        },
            "version": 9,
                "registry": {
            "io.github.annyylxyms.gynrpc.UserService": [
            {
                "scheme": "http",
                    "host": "127.0.0.1",
                    "port": 8081,
                    "context": "gynrpc",
                    "status": true,
                    "parameters": {
                "env": "dev",
                        "tag": "RED"
            }
            }
    ]
        },
            "versions": {
            "io.github.annyylxyms.gynrpc.UserService@http://127.0.0.1:8081/gynrpc": 1725461908849
        },
            "timestamps": {
            "io.github.annyylxyms.gynrpc.UserService": 9
        }
        }*/
    }

    /*public static void main(String[] args) {
        InstanceMeta meta = InstanceMeta.http("127.0.0.1", 8081)
                .addParams(Map.of("env", "dev", "tag", "RED"));
        log.debug(JSON.toJSONString(meta));
    }*/
}
